package isquirrel.recommender;

import isquirrel.beans.Recommendation;
import isquirrel.beans.Url;
import isquirrel.beans.User;
import isquirrel.util.HibernateUtil;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

public class StaticDynamicRecommender extends Recommender {
	
	@SuppressWarnings("unchecked")
	public static List<Recommendation> getRecommendations(User user,
			boolean liked, int howMany, boolean getAbstract) throws UnsupportedEncodingException {
		return proportionsMethod(user, liked, howMany, getAbstract);
	}
	
	@SuppressWarnings("unchecked")
	public static List<Recommendation> simpleMethod(User user,
			boolean liked, int howMany, boolean getAbstract) throws UnsupportedEncodingException {
		//fetch all recommendations
		List<Url> recs = HibernateUtil
				.getSession()
				.createQuery(
						"from Url where user_id = ? and liked = ? order by recommended asc")
				.setLong(0, user.getUserID()).setBoolean(1, liked)
				.list();
		
		return getRandomRecommendations(recs, howMany, getAbstract);
	}
	
	@SuppressWarnings("unchecked")
	public static List<Recommendation> proportionsMethod(User user,
			boolean liked, int howMany, boolean getAbstract) throws UnsupportedEncodingException {
		//fetch all recommendations
		List<Url> staticRecs = HibernateUtil
		.getSession()
		.createQuery(
				"from Url where user_id = ? and liked = ? and source= ? order by recommended asc")
		.setLong(0, user.getUserID()).setBoolean(1, liked).setString(2, "static")
		.list();
		
		List<Url> dynamicRecs = HibernateUtil
		.getSession()
		.createQuery(
				"from Url where user_id = ? and liked = ? and source= ? order by recommended asc")
		.setLong(0, user.getUserID()).setBoolean(1, liked).setString(2, "dynamic")
		.list();
		
		int totalRecs = staticRecs.size() + dynamicRecs.size();
		if (totalRecs == 0) {
			return new ArrayList<Recommendation>();
		}
		int staticProportion = (int) Math.floor(howMany * staticRecs.size() / totalRecs);
		int dynamicProportion = (int) Math.ceil(howMany * dynamicRecs.size() / totalRecs);

		List<Recommendation> staticRecommendations = StaticRecommender.getRecommendations(user, liked, staticProportion, getAbstract);
		List<Recommendation> dynamicRecommendations = DynamicRecommender.getRecommendations(user, liked, dynamicProportion, getAbstract);
		List<Recommendation> recommendations = staticRecommendations;
		recommendations.addAll(dynamicRecommendations);
		return recommendations;
	}
	
	

}
